//
//  ComposeViewController.swift
//  JIMWeiBo
//
//  Created by 陈恒均 on 2018/2/14.
//  Copyright © 2018年 陈恒均. All rights reserved.
//

import UIKit
import SVProgressHUD

class ComposeViewController: UIViewController {

    // MARK:- 约束属性
    @IBOutlet weak var toolBarBottomCons: NSLayoutConstraint!
    @IBOutlet weak var ImagePickViewHCons: NSLayoutConstraint!
    // MARK:- 控件属性
    @IBOutlet weak var picPicker: PicPickerCollectionView!
    @IBOutlet weak var textView: ComposeTextView!
    // MARK:- 懒加载属性
    
    private lazy var titleLabelView :composeTitleView = composeTitleView()
    private lazy var images : [UIImage] = [UIImage]()
    private lazy var emoticonVc : EmoticonViewController = EmoticonViewController {[weak self] (emoticon) in
        self?.textView.insertEmoticon(emoticon: emoticon)
        self?.textViewDidChange(self!.textView)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        textView.delegate = self
        
        setupNav()
        
        setupNotifications()
    }
    
   
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    @IBAction func enmoticon(_ sender: Any) {
        textView.resignFirstResponder()
        
        textView.inputView = textView.inputView != nil ? nil : emoticonVc.view
        
        textView.becomeFirstResponder()
    }
    
    
    @IBAction func imagePickerBtnClick(_ sender: UIButton) {
        
        textView.resignFirstResponder()
        
        if textView.inputView == nil ,textView.inputView == emoticonVc.view {
            picPicker.isHidden = true
            ImagePickViewHCons.constant = 0
        }else{
            ImagePickViewHCons.constant = UIScreen.main.bounds.height * 0.65
            picPicker.isHidden = false
        }
//        ImagePickViewHCons.constant = textView.inputView != nil ?UIScreen.main.bounds.height * 0.65 : 0
        UIView.animate(withDuration: 0.5) {
            
            self.view.layoutIfNeeded()
        }
//        textView.inputView = textView.inputView != nil ? nil : picPicker
//        picPicker.becomeFirstResponder()
    }
    

}
// MARK:- UI界面
extension ComposeViewController{
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(ComposeViewController.closeItemClick))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .plain, target: self, action: #selector(ComposeViewController.sendItemClick))
        
        titleLabelView.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
        navigationItem.titleView = titleLabelView
    }
    
    private func setupNotifications(){
         NotificationCenter.default.addObserver(self, selector: #selector(ComposeViewController.keyboardWillChangeFrame(note:)), name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(addPhotoClick), name: NSNotification.Name(rawValue: PicPickerAddPhotoNote), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(removePhotoClick(note:)), name: Notification.Name(rawValue: PicPickerRemovePhotoNote), object: nil)
    }
}
// MARK:- 事件监听
extension ComposeViewController
{
    @objc func closeItemClick()
    {
        dismiss(animated: true, completion: nil)
    }
    @objc func sendItemClick(){
        print(textView.getEmoticonString())
        textView.resignFirstResponder()
        
        let statusText = textView.getEmoticonString()
        
        let finishedCallBack = { (isSuccess : Bool) in
            if !isSuccess {
                SVProgressHUD.showError(withStatus: "发送微博失败")
                return
            }
            SVProgressHUD.showSuccess(withStatus: "发送微博成功")
            self.dismiss(animated: true, completion: nil)
        }
        
        if let image = images.first{
            NetworkTools.shareInstance.sendStatues(status: statusText, image: image, isSuccess: finishedCallBack)
        }else{
            NetworkTools.shareInstance.sendStatus(status: statusText, isSuccess:finishedCallBack)
        }
        
        
        
        
    }
    @objc func keyboardWillChangeFrame(note : Notification){
        let duration = note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
        
        let endFrame = (note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        
        let y = endFrame.origin.y

        let margin = UIScreen.main.bounds.height - y
        
        toolBarBottomCons.constant = margin
        
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
  
        
    }

}
// MARK:- 增加和删除照片事件
extension ComposeViewController
{
    @objc private func addPhotoClick(){
        if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            return
        }
        let ipc = UIImagePickerController()
        ipc.sourceType = .photoLibrary
        ipc.delegate = self
        present(ipc, animated: true, completion: nil)
      
    }
    
    @objc private func removePhotoClick(note : NSNotification){
        guard let image = note.object as? UIImage else{
            return
        }
        guard let index = images.index(of: image) else {
            return
        }
        images.remove(at: index)
        picPicker.images = images
        
    }
}
// MARK:- 选择照片的代理
extension ComposeViewController : UIImagePickerControllerDelegate , UINavigationControllerDelegate{
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        images.append(image)
        
        
        picPicker.images = images
        
        picker.dismiss(animated: true, completion: nil)
       
    }
}

// MARK:- UITextView的代理方法
extension ComposeViewController : UITextViewDelegate{
    func textViewDidChange(_ textView: UITextView) {
        self.textView.placeholderLabel.isHidden = self.textView.hasText
        navigationItem.rightBarButtonItem?.isEnabled = self.textView.hasText
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.textView.resignFirstResponder()
    }
}


